#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :crud.py
# @Time      :2021/04/06 14:20:19
# @Author    :Raink
# 04

from sqlalchemy.orm import Session
from coronavirus import models, schemas

# 获取城市
def get_city(db: Session, city_id: int):
    return db.query(models.City).filter(models.City.id == city_id).first()

def get_city_by_name(db: Session, name: str):
    return db.query(models.City).filter(models.City.province == name).first()

def get_cities(db: Session, skip:int = 0, limit: int=10):
    return db.query(models.City).order_by(models.City.country_code).offset(skip).limit(limit).all()

# 创建城市
def create_city(db: Session, city:schemas.CreateCity):
    db_city = models.City(**city.dict())
    db.add(db_city)
    db.commit()
    db.refresh(db_city)
    return db_city

# 获取数据
def get_datas(db: Session, city: str=None, skip: int=0, limit: int=10):
    # 如果有城市，按城市查询，如果没有，按照skip和limit去查询
    if city: 
        # 外键关联查询 models.Data里的city关联的是City类，City类中有province属性，
        # 查询的关联的City中province属性等于该函数中“city”的项
        return db.query(models.Data).filter(models.Data.city.has(province=city)).order_by(models.Data.date)
    return db.query(models.Data).order_by(models.Data.date).offset(skip).limit(limit).all()

# 创建城市对应的数据
def create_city_data(db: Session, data: schemas.CreateData, city_id: int):
    db_data = models.Data(**data.dict(), city_id=city_id)
    db.add(db_data)
    db.commit()
    db.refresh(db_data)
    return db_data